const fs = require('fs')
const express = require('express')
const { resolve } = require('path')
const { createRenderer, createBundleRenderer } = require('vue-server-renderer')
const serverBundle = require('../dist/vue-ssr-server-bundle.json')
const clientManiFest = require('../dist/vue-ssr-client-manifest.json')

const server = express()

server.use(express.static(resolve('dist')))
server.get('*', async (req, res, next) => {
  try {
    const path = req.url
    // 1.创建vue实例
    // const app = createApp()
    // 2.创建渲染器
    const serverRenderer = createBundleRenderer(serverBundle, {
      template: fs.readFileSync('./server/index.html', 'utf-8'),
      clientManifest: clientManiFest
    })
    // 3.将vue实例转化为字符串
    const html = await serverRenderer.renderToString({
      url: path
    })
    res.send(html)
  } catch (error) {
    if (error.code === 404) {
      res.status(404).send('页面不存在')
    } else {
      console.log(error)
      res.status(500).send('服务器出错')
    }
  }
})

server.listen(8090, () => {
  console.log('you server is running at http://localhost:8090')
})